package v1

import (
	"fmt"
	"net/http"
	"time"
	"toy-car/models"
	"toy-car/pkg/e"
	"toy-car/pkg/util"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

// 部门信息全部
func DeptList(c *gin.Context) {
	var page, pageSize = util.GetPageAndSize(c)
	listType := c.Query("type")
	dept_name := c.Query("deptName")

	code := e.SUCCESS
	data := make(map[string]interface{})

	if listType == "tree" {
		c.JSON(http.StatusOK, gin.H{
			"code": code,
			"msg":  e.GetMSG(code),
			"data": models.GetAllDeptTree(0, 3),
		})
		return
	}

	list, total, err := models.GetAllDeptList(dept_name, page, pageSize)

	if err != nil {
		code = e.ERROR
	}
	if code != e.SUCCESS {
		e.Fail(e.ERROR, nil, "", c)
		return
	}

	data["page"] = page
	data["pageSize"] = pageSize
	data["data"] = list
	data["total"] = total
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMSG(code),
		"data": data,
	})
}

func DeptAdd(c *gin.Context) {
	var dept models.SysDept

	_ = c.ShouldBindJSON(&dept)
	t := time.Now()
	dept.CreateTime = &t

	// todo 菜单提交数据的校验
	data := make(map[string]interface{})

	err := models.AddSysDept(dept)

	fmt.Println(err)
	if err != nil {
		e.Fail(2000, data, err.Error(), c)
		return
	}

	e.Success(data, "", c)
}

func DeptInfo(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt64()
	dept, err := models.GetASysDept(id)
	code := e.SUCCESS
	if err != nil {
		code = e.ERROR
	}
	if code != e.SUCCESS {
		e.Fail(e.ERROR, nil, "", c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMSG(code),
		"data": dept,
	})
}
func DeptUpdate(c *gin.Context) {
	pid := com.StrTo(c.Param("id")).MustInt64()
	var dept models.SysDept

	_ = c.ShouldBindJSON(&dept)

	dept.ID = pid
	code := e.SUCCESS
	err := models.UpdateSysDept(&dept)
	if err != nil {

		code = e.ERROR
		e.Fail(code, "", err.Error(), c)
	}

	e.Success(dept, "", c)
}

func DeptDelete(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()

	data := make(map[string]interface{})
	code := e.SUCCESS

	// todo 比对删除自己，返回错误
	err := models.DeleteDept(id)
	if err != nil {
		code = e.ERROR
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMSG(code),
		"data": data,
	})
}
